package com.dianshang.elasticsearch;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.util.List;
import java.util.Map;

/**
 * 搜索引擎(ElasticSearch)
 */
public class ElasticSearch6Demo {

    /**
     * 分组聚合查询
     * 按性别为男分组查询，求出每个性别为男的名称
     */
    public static void main(String[] args) throws Exception {
        // 1、创建一个restClient客户端,用于访问ES
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200,"http"); // hostname：本机地址,port：端口号,scheme：HTTP协议
        RestClientBuilder restClientBuilder = RestClient.builder(httpHost); // rest客户端构建器
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder); // rest高级客户端
        // 2、创建一个对应行为的请求对象
        SearchRequest searchRequest = new SearchRequest("zhaoyu"); // 获取索引库名
        searchRequest.types("doc"); // 获取类型名称
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 封装查询条件
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("zhaoyu_category").field("types"); // 获取查询条件
        searchSourceBuilder.aggregation(termsAggregationBuilder); // 用来封装查询条件
        searchSourceBuilder.size(0); // size为0,目的是让查询更快,提高查询效率
        searchRequest.source(searchSourceBuilder); // 存入封装后的查询条件/设置查询条件构造器
        // 3、触发请求,获取响应结果
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        // 4、使用响应的结果
        Aggregations aggregations = searchResponse.getAggregations(); // 获取所有符合要求的数据
        Map<String, Aggregation> map = aggregations.getAsMap(); // 获取所有符合要求的条数
        Terms terms =(Terms) map.get("zhaoyu_category"); // 展示符合要求的所有数据
        List<? extends Terms.Bucket> list = terms.getBuckets();
        for (Terms.Bucket bucket : list) { // 循环遍历符合要求的所有数据
            System.out.println(bucket.getKeyAsString()+":"+bucket.getDocCount()); // getKeyAsString：分组字段名,getDocCount：不同分组字段名的个数
        }
        // 5、关闭ES客户端
        restHighLevelClient.close();
    }

}